<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle rightDrawerWithoutCol"
    style="display: flex; flex-direction: column;"
  >
    <!-- 版本配置 -->
    <a-form-model-item :label="$t('groupVersionConfig')" class="customFormModelItem"> </a-form-model-item>
    <!-- ecu 软件编码 -->
    <a-row :gutter="36">
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="ecuModuleId" label="ECU">
          <a-input-group compact>
          <car-model-code-select
              v-if="showModelCode"
              :query="{ time:instantUpdateTime, selectAll: false}"
              :has-all="false"
              :clear="false"
              :disabled="!!recordData.id || !!fixedEcu"
              v-model="form.modelCode"
              style="width:30%"
              @change="changeEcuListByCarModel"
            ></car-model-code-select>
          <a-select
            ref="ecuSelect"
            v-model="form.ecuModuleId"
            :disabled="!!recordData.id || !!fixedEcu"
            showSearch
            :filterOption="$commonFun.filterOption"
            @change="changeEcuList"
            :placeholder="$t('pleaseSelect') + $t('lingjian')"
            style="width:70%"

          >
            <a-select-option
              v-for="(item, index) in ecuList"
              :key="index"
              :value="item.ecuModuleId"
              :title="`${item.name}/${item.ecuModuleId}`"
            >
              {{ `${item.name}/${item.ecuModuleId}` }}
            </a-select-option>
          </a-select>
          </a-input-group>
        </a-form-model-item>
      </a-col>

      
      <!-- 必须先选零件名称 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="softwareCode" :label="$t('softwareCoding')">
          <a-select
            v-model="form.softwareCode"
            :disabled="!!recordData.id || !form.ecuModuleId"
            showSearch
            allow-clear
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            :placeholder="form.ecuModuleId ? $t('pleaseSelect') + $t('softwareCoding') : $t('firstSelectEcu')"
          >
            <a-select-option
              v-for="(item, index) in filterEcuList"
              :key="index"
              :value="item.softwareCode"
              :title="item.softwareCode"
            >
              {{ item.softwareCode }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>

    <!-- 版本名称 兼容版本 -->
    <a-row :gutter="36">
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="name">
          <template slot="label">
            {{ $t('versionName') }}
            <question-mark-tip
              :tip-title="$t('inputVersionNameWithoutVTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-input v-model="form.name" :disabled="!!recordData.id" />
        </a-form-model-item>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-form-model-item>
          <template slot="label">
            {{ $t('dependencyVersion') }}
            <question-mark-tip
              :tip-title="$t('dependencyVersionTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <VersionSelect v-model="selectedDependenceVersion" :clear="true" mode="multiple" onlyVersionType="TEST"
                         :ecuModuleId="form.ecuModuleId"
                         :targetVersionId="targetVersionId"
                         :replace-fields="{key:'name', value:'name',title:'name'}"
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    <!--兼容版本 <a-form-model-item>
          <template slot="label">
            {{ $t('dependencyVersion') }}
            <question-mark-tip
              :tip-title="$t('dependencyVersionTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <VersionSelect v-model="selectedDependenceVersion" :clear="true" mode="multiple" onlyVersionType="TEST"
                         :ecuModuleId="form.ecuModuleId"
                         :targetVersionId="targetVersionId"
                         :replace-fields="{key:'name', value:'name',title:'name'}"
          />
        </a-form-model-item> -->
    <!-- 版本编号  -->
    <a-row :gutter="36">
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="code">
          <template v-slot:label>
            <span>{{ $t('versionCode') }}</span>
            <question-mark-tip
              :tip-title="$t('partVersionCodeTip')"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </template>
          <a-input v-model="form.code" />
        </a-form-model-item>
      </a-col>
      <!-- 硬件版本号 硬件版本编号 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item  :label="$t('hardVersion')">
          <a-input :maxLength="60" v-model="form.hardVersion" />
        </a-form-model-item>
      </a-col>
   </a-row>
    <!-- 硬件版本日期  -->
    <a-row :gutter="36">
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="hardVersionDate" :label="$t('hardVersionDate')">
          <a-date-picker
            v-model="form.hardVersionDate"
            format="YYYY-MM-DD"
            :disabledDate="disabledEndDate"
            :popupContainer="$commonFun.getPopupContainer"
            style="width: 100%"
            @change="onChangeDate"
          />
        </a-form-model-item>
      </a-col>
      <!-- DLL文件类名 -->
      <a-col :md="12" :sm="24">
        <a-form-model-item prop="dllName" :label="$t('dllFileClassName')">
          <a-select :placeholder="$t('dllPlaceholder')" v-model="form.dllName" showSearch  :filterOption="$commonFun.filterOption">
            <a-select-option
              v-for="item in dllClassNameDictCode"
              :key="item.value"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
      <!-- svn日期 判断表单类型决定是否隐藏 -->
       <a-col :md="12" :sm="24" v-if="(recordData.formType==='AUTO')">
         <a-form-model-item prop="svnDate" label="SVN日期">
           <a-date-picker
            v-model="recordData.svnDate"
            format="YYYY-MM-DD"
            disabled           
            style="width: 100%"    
          />
          </a-form-model-item>
      </a-col>
    </a-row>
    <!-- 版本文件 -->
    <!-- <div style="position:relative" >
      <a-form-model-item :label="$t('versionFile')" class="customFormModelItem">
      </a-form-model-item>
      <a style="position:absolute;left:120px;top:0" @click="addFiles">{{ $t('upload') }}</a>
    </div>
    <a-table
      ref="table"
      size="default"
      :row-key="(record,index)=>index"
      :columns="columns"
      :data-source="fileList"
      :pagination="false"
    >
      <template
        slot="fileName"
        slot-scope="text,record"
      >
        <table-ellipsis :text="recordData.id?record.name:record.fileName"></table-ellipsis>
      </template>
      <template
        slot="fileStatus"
        slot-scope="text,record"
      >
        {{ fileStatusDictCodeObj[record.status]||'-' }}
      </template>
      <template
        slot="action"
        slot-scope="text,record"
      >
        <a @click="deleteVersionFile(record)">{{ $t('delete') }}</a>
      </template>
    </a-table> -->
     <!-- SVN地址 -->
    <a-form-model-item label="SVN地址" v-if="(recordData.formType==='AUTO')" class="customFormModelItem">
    <div>
      <a-row :gutter="20">
        <a-col :span="18">
          <a-input disabled v-model="recordData.svnPath"  placeholder="单行输入"></a-input>
        </a-col
      >
     <a-col :span="4">
         <a-switch  style="margin-top:4px" checked-children="启用" un-checked-children="暂停" :checked="pathStatus"  @click="handlerIsGetResourceByPath"></a-switch>
      </a-col>
      </a-row>
    </div>
    </a-form-model-item>
    <!-- ECU信息 -->
    <div style="margin-top: 24px; margin-bottom: 24px">
      <a-form-model-item :label="$t('ecuInfo')" class="customFormModelItem"> </a-form-model-item>
      <div>
        <parts-infor-list
          :refrenshTime="refrenshTime"
          :query="{ ecuModuleId: form.ecuModuleId || '' }"
        ></parts-infor-list>
      </div>
    </div>
    <!-- 配置文件版本 -->
    <a-form-model-item :label="$t('configFileVersion')" class="customFormModelItem"> </a-form-model-item>
    <a-row :gutter="36">
      <a-col :md="24">
        <a-form-model-item label="">
          <a-select
            v-model="form.configVersionId"
            showSearch
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            allow-clear
          >
            <a-select-option
              v-for="(item, index) in configFileVersionSelect"
              :key="index"
              :value="item.id"
              :title="item.name"
            >
              {{ item.name }} 【{{$store.getters.getDictCodeObj('versionTypeDictCode')[item.versionType] || item.versionType}}】
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <!-- 发布说明 -->
    <div class="releaseNoteBox">
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('releaseNote')" class="customFormModelItem"></a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 版本描述 -->
          <a-form-model-item :label="$t('versionDescription')" prop="description">
            <custom-text-area
              @change="handlerChange('description', $event)"
              :val="form.description"
              :max-len="500"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 功能新增 -->
          <a-form-model-item :label="$t('funcAdd')" prop="functionAddition">
            <custom-text-area
              @change="handlerChange('functionAddition', $event)"
              :val="form.functionAddition"
              :max-len="500"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 功能优化 -->
          <a-form-model-item :label="$t('funcOptimize')" prop="functionOptimization">
            <custom-text-area
              @change="handlerChange('functionOptimization', $event)"
              :val="form.functionOptimization"
              :max-len="500"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 特别鸣谢 -->
          <a-form-model-item :label="$t('specialThanks')" prop="acknowledgements">
            <custom-text-area
              @change="handlerChange('acknowledgements', $event)"
              :val="form.acknowledgements"
              :max-len="500"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
    </div>
    <!-- 上传版本文件 -->
    <upload-part-version-file ref="uploadFile" @saveFile="uploadOk"></upload-part-version-file>
  </a-form-model>
</template>
<script>
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapState } from 'vuex'
import UploadPartVersionFile from './UploadPartVersionFile.vue'
import PartsInforList from '../../components/PartsInforList.vue'
import LangSelect from '@/views/components/LangSelect'
import VersionSelect from '@/views/components/VersionSelect'
import moment from 'moment'
import lodash from 'lodash'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import { checkVersionNameWithOutV, checkTextLen } from '@/utils/validate'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import ecuApi from '@/api/modules/system/ecuMana'


const initForm = {
  ecuModuleId: undefined,
  softwareCode: undefined,
  dllName:undefined,
  configVersionId: undefined,
  // 版本描述
  description: '',
  // 功能新增
  functionAddition: '',
  // 功能优化
  functionOptimization: '',
  // 特别鸣谢
  acknowledgements: ''
}
export default {
  name: 'NewVersion',
  components: {
    TableEllipsis,
    PartsInforList,
    LangSelect,
    VersionSelect,
    UploadPartVersionFile,
    QuestionMarkTip,
    CustomTextArea,
    CarModelCodeSelect
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    fixedEcu: {
      type: Object,
      default: () => {
        return null
      }
    },
     showModelCode: {
       type: Boolean,
       default: () => {
        return true
       }
     }
  },
  computed: {
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      dllClassNameDictCode: (state) => state.dict.dllClassNameDictCode,
    }),
    fileStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('fileStatusDictCode')
    },
    columns () {
      // 表头
      const columns = [
        {
          title: this.$t('fileName'),
          scopedSlots: { customRender: 'fileName' },
          width: '45%'
        },
        {
          title: this.$t('fileStatus'),
          scopedSlots: { customRender: 'fileStatus' },
          width: '35%'
        },
        {
          title: this.$t('operation'),
          width: '20%',
          scopedSlots: { customRender: 'action' }
        }
      ]
      return columns
    }
  },
  data () {
    return {
      selectedDependenceVersion: [],
      selectedTab: null,
      form: lodash.cloneDeep(initForm),
      rules: {
        ecuModuleId: [{ required: true, message: this.$t('pleaseSelect') }],
         name: [
          { required: true, message: this.$t('pleaseInput') },
          // lxhmodifyxccode
          {
            validator: checkVersionNameWithOutV()
          }
        ], 
        softwareCode: [{ required: true, message: this.$t('pleaseSelect') }],
        code: [{ required: true, pattern: /^[1-9][0-9]{0,16}$/, message: this.$t('digits17') }],
        hardVersion: [{ validator: checkTextLen(60, true) }],
        description: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        /* svn日期 */
         svnDate: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionAddition: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionOptimization: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(500, true) }
        ],
        dllName: [{ required: true, message: this.$t('pleaseSelect') }],
      },
      configSoftwareCode: '',
      configFileVersionSelect: [], // 配置文件版本列表
      selectedEcuList: [], // 已选中ecu
      ecuList: [], // 零件名称下拉数据（去重）
      filterEcuList: [], // 软件编码下拉数据
      fileList: [],
      targetVersionId: '', // 编辑时的零件版本id
      refrenshTime: 1, // 监听刷新零件信息
      isSearch: false,
      modelName: undefined,
      pathStatus:this.recordData.svnEnabled
    }
  },
  mounted () {
    this.initDataForm()
    this.$store.dispatch('getFileStatusDictCodeData')
    this.$store.dispatch('getDllClassNameDictCodeData')
  },
  methods: {
    // 日期变化
    onChangeDate (val1, formatedDate) {
      this.form.hardVersionDate = formatedDate
    },
    // 硬件版本日期的日期选择的禁选日期
    disabledEndDate (current) {
      return current && current > moment().endOf('day')
    },
    handlerChange (key, val) {
      this.form[key] = val
    },
    initDataForm () {
      const vm = this
      vm.fileList = [] // 初始化版本信息表格
      vm.targetVersionId = '' // 初始化没有零件版本id
      vm.$refs.ruleForm && vm.$refs.ruleForm.resetFields()
      //vm.getEcuList().then(() => {
        if(this.fixedEcu){
          vm.$nextTick(()=>{
            vm.$set(vm.form, 'ecuModuleId', this.fixedEcu.ecuModuleId)
            vm.$set(vm.form, 'modelCode', this.fixedEcu.modelCode)
          })
        }
        if (vm.recordData.id) {
          //   编辑
          vm.getVersionInfor().then(res => {
            vm.form = {
              ...res,
              configVersionId: res.configVersionId,
              // 为了兼容xc以前写的代码，所以在下面添加的属性
              description: res.description,
              functionAddition: res.functionAddition,
              functionOptimization: res.functionOptimization,
              acknowledgements: res.acknowledgements
            }
            vm.$set(vm.form, 'ecuName', res.ecu.name)
            if (res.dependenceVersion) {
              // vm.$set(vm.form, 'dependenceVersion', res.dependenceVersion.split(','))
              vm.selectedDependenceVersion =  res.dependenceVersion.split(',');
            }
            vm.fileList = res.materialFile ? [res.materialFile] : []
            vm.targetVersionId = res.id
            // 编辑时根据选中的软件编码获取配置文件版本下拉数据
            vm.configSoftwareCode = res.configSoftwareCode
            vm.getConfigFileVersionList()
            vm.$api.getAllEcu({ ecuModuleId: res.ecuModuleId }).then((res) => {
              vm.ecuList = res.data || []
            })
          })
        } else {
          //   新增
          vm.form = lodash.cloneDeep(initForm)
          vm.$set(vm.form, 'code', moment(new Date().getTime()).format('YYYYMMDDHHmmss'))
          vm.configSoftwareCode = ''
        }
      //})
    },
    // 获取版本详情
    getVersionInfor () {
      const vm = this
      return new Promise((resolve, reject) => {
        vm.$api
          .versionInfor({ id: this.recordData.id })
          .then((response) => {
            resolve(response.data)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 获取配置文件版本下拉框val
    getConfigFileVersionList (val) {
      const vm = this
      vm.configFileVersionSelect = [] // 初始化
      if (!val) return
      vm.$api.configFileSelect({ ecuModuleId: val, versionType: 'TEST' }).then((response) => {
        vm.configFileVersionSelect = response.data
      })
    },
    // 获取已选中ecu的下拉数据
    changeEcuList (value) {
      const vm = this
      vm.selectedEcuList = []
      if (value) {
        const selectItem = vm.ecuList.filter((item) => item.ecuModuleId === value)
        vm.selectedEcuList = selectItem
      } else {
        // vm.ecuList = []
        vm.form.softwareCode = undefined
      }
      this.$refs.ruleForm.validateField('ecuModuleId')
    },
    getEcuList (value) {
      const vm = this
      vm.ecuList = []
      vm.isSearch = false
      if (value) {
        vm.isSearch = true
        vm.$api.getAllEcu({ name: value.trim(), code: this.form.modelCode }).then((res) => {
          vm.ecuList = res.data || []
        })
      } else {
        vm.ecuList = vm.selectedEcuList
      }
    },
     //启用或暂停svnPath获取包
    handlerIsGetResourceByPath(){  
      this.pathStatus=!this.pathStatus;
     this.$api.isGetResourceByPath({
      targetVersionId: this.recordData.id,
      enabled:this.pathStatus,
      svnPath:this.recordData.svnPath
      }).then(res=>{
      console.log(res);
    console.log(this.recordData);
     this.recordData.refreshData();
      })}
    ,
    // 添加文件
    addFiles () {
      this.$refs.uploadFile.addFiles()
    },
    // 上传提交
    uploadOk (formUploadFile) {
      this.fileList = [formUploadFile]
    },
    deleteVersionFile () {
      const vm = this
      this.$confirm({
        title: vm.$t('delete'),
        content: '请确认是否删除？删除后将无法恢复！',
        onOk: this.deleteVersionFileOk,
        onCancel () {}
      })
    },
    deleteVersionFileOk () {
      const vm = this
      vm.fileList = []
      vm.$set(vm.form, 'materialFileId', undefined)
    },
    getFormData () {
      const vm = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            reject(valid)
            return
          }
          resolve(vm.getFormDataFun())
        })
      })
    },
    getFormDataFun () {
      const vm = this
      vm.form.configSoftwareCode = vm.configSoftwareCode
      if (vm.fileList.length) {
        vm.form.materialFileId = vm.fileList[0].fileId
      }
      let resultP = {}
      if (vm.form.id) {
        resultP = {
          id: vm.form.id,
          name: vm.form.name,
          softwareDid: vm.form.softwareCode,
          code: vm.form.code,
          materialFileId: vm.form.materialFileId,
          configVersionId: vm.form.configVersionId,
          configSoftwareCode: vm.form.configSoftwareCode,
          description: vm.form.description,
          functionAddition: vm.form.functionAddition,
          functionOptimization: vm.form.functionOptimization,
          acknowledgements: vm.form.acknowledgements,
          hardVersion: vm.form.hardVersion,
          hardVersionDate: vm.form.hardVersionDate,
          dllName:vm.form.dllName,
          apiStr: 'editVersion'
        }
      } else {
        resultP = lodash.cloneDeep(vm.form)
        resultP.apiStr = 'addVersion'
      }
      if (vm.selectedDependenceVersion && vm.selectedDependenceVersion.length) {
        resultP.dependenceVersion = vm.selectedDependenceVersion.join(',')
      } else {
        resultP.dependenceVersion = ''
      }
      return resultP
    },
    changeEcuListByCarModel(value) {
        // 根据车型ID获取ecu列表
      this.$refs.ecuSelect.focus();
      if (value) {
        ecuApi.getEcuListByModelCode({"code": value}).then(res => {
          this.ecuList = res.data
        });
      } else {
        // this.ecuList = [];
      }
      // if(value === undefined){
        this.form.ecuModuleId=undefined
      // }
    }
  },
  /**
   *
   */
  watch: {
    instantUpdateTime: {
      handler () {
        // this.initDataForm()
      },
      immediate: true
    },
    'form.modelCode'(val){
      this.$refs.ruleForm.clearValidate('ecuModuleId')
      if (!this.recordData.id && val) {
        this.form.softwareCode = undefined
      }
    },
    'form.ecuModuleId' (val) {
      const vm = this
      // 获取软件编码下拉数据
      if (!vm.recordData.id && val) {
        vm.form.softwareCode = undefined
        vm.filterEcuList = []
        vm.$api.getAllEcu({ ecuModuleId: val }).then((res) => {
          vm.filterEcuList = vm.filterEcuList.concat(res.data)
        })
      }
      // 获取零件信息
      vm.refrenshTime = Date.now()
      // 获取兼容版本
      if (!vm.recordData.id) {
        vm.$set(vm.form, 'dependenceVersion', undefined)
      }
      // 配置文件版本
      vm.getConfigFileVersionList(val)
      if (!vm.recordData.id) {
        vm.form.configVersionId = undefined
      }
    }
  }
}
</script>

